import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Spin } from 'antd';
import ProductComp from './nonStandardProduct';
import BaseInfoForm from './nonStandardProduct/baseInfoForm';
import PortfolioSetting from './nonStandardProduct/portfolioSetting';
import TradeTrial from './tradeTrial';
import myStyle from './style.less';
import dataConfig from '../dataConfig';
import ProductAnalysis from './productAnalysis';
import NonStardardInfo from './nonStardardInfo';
import AddTradeC from './addTrade';
import BatchConfirm from './nonStardardInfo/batchConfirm'; // 历史定价结果
import UpdataForm from './nonStardardInfo/updataForm';

@connect(({ loading, workStationM }) => ({
  loading,
  workStationM,
}))
export default class NonstandardStation extends PureComponent {
  state = {
    showOnly: undefined, // 展示一行还是两行
    stateObj: {
      // productState:15,//非标产品,
      // tradeTrialState:15,//交易试算
      // nonStardardInfoState:15,//非标信息
      // analysisState:15,//产品分析
    },
    productCode: undefined, // 产品组合选中的code
    loadingStatus: undefined, // 页面加载 true false
    pageState: '1', // pageState:1-主页面 2-新增产品 3-组合设置  4-新增非标基本信息  5-编辑非标信息 6- 批量复核
    rootId: undefined, // 组合根节点id 给组合设置使用
    productName: undefined, // 产品名称
    productId: undefined, // 产品id
    modes: '', // 交易模式
  };

  UNSAFE_componentWillMount() {
    // 监听浏览器窗口变化 得到屏幕大小
    window.addEventListener('resize', this.windowChange);
    this.windowChange();
    this.setState({
      // loadingStatus:true
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  // 窗口变化 确定显示一行单个 还是一行两个
  windowChange = () => {
    const width = document.body?.clientWidth;
    const { showOnly } = this.state;
    console.log(showOnly);
    this.setState(
      {
        showOnly: width < dataConfig.dividingSize,
      },
      () => {
        if (showOnly == undefined) {
          console.log('&&&');
          /**
				 *  非标产品：<1920，state=2； >=1920，state=15
					交易试算：<1920，state=2； >=1920，state=15
					产品分析：<1920，state=2； >=1920，state=15
					非标信息：<1920，state=2； >=1920，state=15
				* */
          this.setState({
            stateObj: {
              productState: this.state.showOnly ? '2' : '15',
              tradeTrialState: this.state.showOnly ? '2' : '15',
              nonStardardInfoState: this.state.showOnly ? '2' : '15',
              analysisState: this.state.showOnly ? '2' : '15',
            },
          });
          return;
        }
        const { stateObj } = this.state;
        // 窗口变化  状态需要改变 11和1  是不一样的意思 必须要转换
        if (showOnly != undefined && showOnly != this.state.showOnly) {
          if (stateObj.productState < 10) {
            this.setState({
              stateObj: {
                productState: '15',
                tradeTrialState: '15',
                nonStardardInfoState: '15',
                analysisState: '15',
              },
            });
          } else if (['11', '13', '15'].includes(stateObj.productState)) {
            this.setState({
              stateObj: {
                productState: '2',
                tradeTrialState: '2',
                nonStardardInfoState: '2',
                analysisState: '2',
              },
            });
          }
        }
      },
    );
  };

  componentWillUnmount() {
    // 删除窗口大小的监听
    window.removeEventListener('resize', this.windowChange);
  }

  /**
	 * 拆分成四个大组件：非标产品、产品分析、交易试算、非标信息，每个组件有以下几个状态，组件应该是什么状态，应该是框架分析后，向组件内部传入状态。
	state=1：<1920 折叠 选择了产品
	state=2：<1920 展开 选择了产品
	state=11：>=1920 单折叠 选择了产品
	state=13：>=1920 双折叠 选择了产品
	state=15：>=1920 展开 选择了产品
	*/
  // 1920改变展开折叠状态
  changeState = (type, type1) => {
    const { stateObj } = this.state;
    let leftStatus = stateObj[type];
    let rightStatus = stateObj[type1];
    console.log(leftStatus, rightStatus);

    // 右侧单折叠
    if (leftStatus == '15' && rightStatus == '11') {
      leftStatus = '13';
      rightStatus = '13';
      console.log('***1**');
    } else if (leftStatus == '16' && rightStatus == '12') {
      leftStatus = '14';
      rightStatus = '14';
      console.log('***2**');
    }
    // 右侧展开
    else if (leftStatus == '15' && rightStatus == '15') {
      leftStatus = '11';
      rightStatus = '15';
      console.log('***3**');
    } else if (leftStatus == '16' && rightStatus == '16') {
      leftStatus = '12';
      rightStatus = '16';
      console.log('***4**');
    }
    // 双折叠选择组合
    else if (leftStatus == '13' && rightStatus == '13') {
      leftStatus = '15';
      rightStatus = '11';
      console.log('***5**');
    }
    // 双折叠未选择组合
    else if (leftStatus == '14' && rightStatus == '14') {
      leftStatus = '16';
      rightStatus = '12'; // 少一个都展开的状态
      console.log('***6**');
    }
    // 左侧单折叠 右侧展开
    else if (leftStatus == '11' && rightStatus == '15') {
      leftStatus = '15';
      rightStatus = '15';
      console.log('***7**');
    } else if (leftStatus == '12' && rightStatus == '16') {
      leftStatus = '16';
      rightStatus = '16';
      console.log('***8**');
    }
    console.log(leftStatus);
    stateObj[type] = leftStatus;
    stateObj[type1] = rightStatus;
    this.setState({
      stateObj: { ...stateObj },
    });
    // }
  };

  // 小于1920 展开折叠状态改变
  onlyChangeStatus = (e, type) => {
    const { stateObj } = this.state;
    let data = stateObj[type];
    if (data == 1) {
      data = '2';
    } else if (data == 2) {
      data = '1';
    }
    stateObj[type] = data;
    this.setState({
      stateObj: { ...stateObj },
    });
  };

  // 产品选择变更事件productOnChange
  productOnChange = (code, name, productId, type) => {
    console.log(code, '拿到子组件给的code', type);
    this.setState(
      {
        productCode: code,
        productName: name,
        productId,
      },
      () => {
        if (type) {
          // 关联持仓点击了产品建简称，传递code给框架，非标产品中定位的产品需根据产品code重新定位，交易试算重新加载
          this.state.myProductRef?.refresh();
          this.state.TradeTrial?.refresh();
        }
      },
    );
  };

  // 改变是否显示主页面
  changePage = (e, type) => {
    this.setState({
      pageState: e,
    });
    // if(e==1){//回到主页清空产品id
    // 	this.setState({
    // 		rootId:undefined,//清空产品id
    // 	})
    // }
    if (type == 'refreshPrice') {
      // 刷新历史定价
      this.state.NonStardardInfo?.refreshPrice();
    }
  };

  // 证券代码变更 并通知给非标信息组件 标的种类（7-非标(理财直融) 12- 非标(非理财直融)）、标的代码
  securityCodeChange = (record) => {
    this.setState({
      record,
    });
  };

  // 新增产品成功 通知产品组件刷新 并回到主页
  addNewProduct = () => {
    this.setState({
      pageState: 1,
    });
    this.state.myProductRef?.refresh();
  };

  // 资金调整成功 通知交易试算刷新 并回到主页
  fundChange = () => {
    this.setState({
      pageState: 1,
    });
    // 调用交易试算的更新方法refresh
    this.state.TradeTrial?.refresh();
  };

  // 子组合新增成功 通知交易试算刷新 并回到主页
  addChildProduct = () => {
    this.setState({
      pageState: 1,
    });
    // 调用交易试算的更新方法refresh
    this.state.TradeTrial?.refresh();
  };

  // 获取产品id 给到组合设置组件
  getRootId = (id, gzCode) => {
    console.log(id, '***');
    this.setState({
      rootId: id,
      gzCode,
    });
  };

  // 非标信息新增/编辑时调用，改变标的类型
  securityTypeChange = (type) => {
    console.log(type, '***');
    this.setState({
      securityType: type, // 标的类型：7-非标(理财直融) 12- 非标(非理财直融)）
    });
  };

  // 切换产品，获取交易模式
  getModes = (modes) => {
    this.setState({
      modes,
    });
  };

  render() {
    const { showOnly, productCode, loadingStatus, pageState, securityType, securityName, securityCode, modes } = this.state;
    const { productState, tradeTrialState, analysisState, nonStardardInfoState } = this.state.stateObj;
    const formatStyle = (data0, data1) => {
      let width;
      if ((data0 == 16 && data1 == 12) || (data0 == 15 && data1 == 11)) {
        // 左侧展开 右侧收缩
        width = `calc(100% - ${dataConfig.shrinkSize.width} - 24px)`;
      } else if (data0 == 11 || data0 == 12) {
        // 左侧单折叠
        width = dataConfig.shrinkSize.width;
      } else {
        // 自适应
        width = undefined;
      }
      return width;
    };
    const formatHeight = (data, data0, type) => {
      let height;
      height = ['1', '3'].includes(data) ? dataConfig.shrinkSize.height : ['2', '4'].includes(data) ? 'auto' : type ? (['11', '12'].includes(data) ? '570px' : 'auto') : '570px';
      if ((data == 13 && data0 == 13) || (data == 14 && data0 == 14)) {
        // 双折叠高度
        height = dataConfig.shrinkSize.height;
      }
      return height;
    };

    return (
      <div style={{ height: '100vh' }}>
        <div
          style={{ display: pageState == 1 ? 'inherit' : 'none' }}
          className={showOnly ? `${myStyle.barraStation} ${myStyle.showOnly}` : `${myStyle.barraStation}  ${myStyle.showMore}`}
        >
          {loadingStatus ? (
            <Spin spinning={loadingStatus} style={{ height: 'calc(100vh - 54px', width: '100%' }}>
              <div></div>
            </Spin>
          ) : (
            <div>
              <div
                style={{
                  height: formatHeight(productState, tradeTrialState),
                  width: formatStyle(productState, tradeTrialState),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                <ProductComp
                  state={productState}
                  productCode={productCode}
                  productOnChange={this.productOnChange}
                  changePage={this.changePage}
                  addNewProduct={this.addNewProduct}
                  fundChange={this.fundChange}
                  addChildProduct={this.addChildProduct}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'productState') : this.changeState('productState', 'tradeTrialState');
                  }}
                  onRef={(ref) => (this.state.myProductRef = ref)}
                  getRootId={this.getRootId}
                  getModes={this.getModes}
                />
              </div>
              <div
                style={{
                  order: showOnly ? 3 : 'inherit',
                  height: formatHeight(tradeTrialState, productState),
                  width: formatStyle(tradeTrialState, productState),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                <TradeTrial
                  onRef={(ref) => (this.state.TradeTrial = ref)}
                  state={tradeTrialState}
                  productCode={productCode}
                  securityCodeChange={this.securityCodeChange}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'tradeTrialState') : this.changeState('tradeTrialState', 'productState');
                  }}
                  modes={modes}
                />
              </div>
              <div
                style={{
                  order: showOnly ? 2 : 'inherit',
                  height: formatHeight(analysisState, nonStardardInfoState, 'bottom'),
                  width: formatStyle(analysisState, nonStardardInfoState),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                <ProductAnalysis
                  state={analysisState}
                  productCode={productCode}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'analysisState') : this.changeState('analysisState', 'nonStardardInfoState');
                  }}
                  rootId={this.state.rootId}
                  productName={this.state.productName}
                />
              </div>

              <div
                style={{
                  order: showOnly ? 3 : 'inherit',
                  height: formatHeight(nonStardardInfoState, analysisState, 'bottom'),
                  width: formatStyle(nonStardardInfoState, analysisState),
                  minWidth: showOnly ? dataConfig.compMinWidth : 'auto',
                }}
              >
                <NonStardardInfo
                  onRef={(ref) => (this.state.NonStardardInfo = ref)}
                  state={nonStardardInfoState}
                  productCode={productCode}
                  record={this.state.record || {}}
                  changePage={this.changePage}
                  gzCode={this.state.gzCode}
                  rootId={this.state.rootId}
                  securityTypeChange={this.securityTypeChange}
                  productOnChange={(e) => this.productOnChange(e, null, 'refresh')}
                  stateOnChange={(e) => {
                    showOnly ? this.onlyChangeStatus(e, 'nonStardardInfoState') : this.changeState('nonStardardInfoState', 'analysisState');
                  }}
                  modes={modes}
                />
              </div>
            </div>
          )}
          <ul style={{ display: 'inherit', position: 'fixed', top: '150px', margin: 0, padding: 0, right: 0, zIndex: 10 }}>
            <AddTradeC
              // portfolioCode={portfolioCode}
              productCode={productCode}
              tradeTrialRefresh={this.TradeTrial?.refresh()}
              rootId={this.state.rootId}
              modes={modes}
            />
          </ul>
        </div>
        {pageState > 1 && (
          <div className={`${myStyle.barraStation}`}>
            {pageState == '2' && <BaseInfoForm productId={productCode} addNewProduct={this.addNewProduct} changePage={this.changePage} />}
            {pageState == '3' && <PortfolioSetting productId={productCode} addChildProduct={this.addChildProduct} changePage={this.changePage} rootId={this.state.rootId} />}
            {pageState == '6' && <BatchConfirm changePage={this.changePage} />}
            {(pageState == '4' || pageState == '5') && (
              <UpdataForm securityType={securityType} pageState={pageState} record={this.state.record || {}} changePage={this.changePage} />
            )}
          </div>
        )}
      </div>
    );
  }
}
